<script setup>
import { ref, onMounted } from "vue";
import * as echarts from "echarts";

const chartRef = ref(null);
let chart = null;

const initChart = () => {
  if (!chartRef.value) return;

  chart = echarts.init(chartRef.value);
  const chartData = [
    { value: 1, name: "A" },
    { value: 2, name: "B" },
    { value: 11, name: "C" },
    { value: 2, name: "D" },
    { value: 1, name: "E" },
    { value: 4, name: "F" },
    { value: 64, name: "G" },
    { value: 2, name: "H" },
    { value: 4, name: "I" },
    { value: 1, name: "J" },
    { value: 1, name: "K" }
  ].map(item => ({
    ...item,
    value: Math.log10(item.value + 1) // 对数转换，加1避免log(0)
  }));
  const option = {
    tooltip: {
      trigger: "item",
      formatter: function(params) {
        const originalValue = Math.pow(10, params.value) - 1; // 还原原始值
        return `${params.name} : ${originalValue.toFixed(2)}`;
      },
    },
    legend: {
      orient: "vertical",
      right: 50,
      top: "center",
      itemGap: 20,
      itemWidth: 20,
      itemHeight: 20,
      textStyle: {
        padding: [0, 0, 0, 10]
      },
      data: chartData.map(item => item.name),
      formatter: function (name) {
        const item = chartData.find((item) => item.name === name);
        const originalValue = Math.pow(10, item.value) - 1; // 还原原始值
        return `${originalValue.toFixed(0)}`;
      },
      grid: {
        left: '10%',
        right: '10%',
        top: 'middle',
        bottom: 'middle',
        containLabel: true
      },
      columns: 2 // 设置两列显示
    },
    color: [
      '#E41E25', // 鲜红
      '#009E73', // 翠绿
      '#0072B2', // 深蓝
      '#FFD700', // 金色
      '#FF69B4', // 亮粉红
      '#F28522', // 亮橙
      '#8A2BE2', // 紫罗兰
      '#20B2AA', // 浅海绿
      '#FF4500', // 橙红色
      '#00CED1', // 深青色
      '#DEB887'  // 实木色
    ],
    series: [
      {
        name: "面积模式",
        type: "pie",
        radius: [30, 110],
        center: ["50%", "50%"],
        roseType: "area",
        itemStyle: {
          borderRadius: 8,
        },
        data: chartData,
      },
    ],
  };

  chart.setOption(option);
};

onMounted(() => {
  initChart();
  window.addEventListener("resize", () => {
    chart?.resize();
  });
});
</script>

<template>
  <div class="rose-chart-container">
    <div ref="chartRef" class="rose-chart"></div>
  </div>
</template>

<style scoped>
.rose-chart-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.rose-chart {
  width: 800px;
  height: 250px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
